package com.joolun.mall.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.joolun.common.utils.DateUtils;
import com.joolun.common.utils.uuid.UUID;
import com.joolun.mall.config.AliyunOSSConfig;
import com.joolun.mall.domain.vo.FileVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class AliyunOSSService {
    
    private final AliyunOSSConfig aliyunOSSConfig;

    public static String uuid() {
        return java.util.UUID.randomUUID().toString().replaceAll("\\-", "").toLowerCase();
    }

    /**
     * 上传文件到OSS
     * @param file 文件
     * @param folder 上传到的文件夹
     * @return 文件访问URL
     */
    public FileVO uploadFile(MultipartFile file, String folder) {
        // 验证文件
        validateFile(file);
        
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(
                aliyunOSSConfig.getEndpoint(), 
                aliyunOSSConfig.getAccessKeyId(), 
                aliyunOSSConfig.getAccessKeySecret());
        
        try {
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = uuid() + fileExtension;
            
            // 构建文件路径
            String filePath = folder + DateUtils.parseDateToStr("/yyyy/MM/dd/",new Date()) + fileName;
            
            // 上传文件流
            ossClient.putObject(aliyunOSSConfig.getBucketName(), filePath, file.getInputStream());
            String url = filePath;
            FileVO fileVO = new FileVO();
            fileVO.setFileName(originalFilename);
            fileVO.setUrl(url);
            // 返回文件URL
            return fileVO;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    
    /**
     * 验证文件是否符合要求
     */
    private void validateFile(MultipartFile file) {
        // 检查文件大小
        long maxSize = parseSize(aliyunOSSConfig.getMaxFileSize());
        if (file.getSize() > maxSize) {
            throw new RuntimeException("文件大小不能超过 " + aliyunOSSConfig.getMaxFileSize());
        }
        
        // 检查文件扩展名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        
//        List<String> allowedExtensions = Arrays.asList(aliyunOSSConfig.getAllowedExtensions().split(","));
//        if (!allowedExtensions.contains(fileExtension)) {
//            throw new RuntimeException("不支持的文件类型，仅支持: " + aliyunOSSConfig.getAllowedExtensions());
//        }
    }
    
    /**
     * 生成文件访问URL
     */
    private String generateFileUrl(String filePath) {
        return "https://" + aliyunOSSConfig.getBucketName() + "." + aliyunOSSConfig.getEndpoint() + "/" + filePath;
    }
    
    /**
     * 将字符串格式的文件大小转换为字节数
     */
    private long parseSize(String size) {
        size = size.toUpperCase();
        if (size.endsWith("KB")) {
            return Long.parseLong(size.substring(0, size.length() - 2)) * 1024;
        } else if (size.endsWith("MB")) {
            return Long.parseLong(size.substring(0, size.length() - 2)) * 1024 * 1024;
        } else if (size.endsWith("GB")) {
            return Long.parseLong(size.substring(0, size.length() - 2)) * 1024 * 1024 * 1024;
        } else {
            return Long.parseLong(size);
        }
    }
}